<?php
namespace App\Ext\Xunsearch;

//include 'sdk/php/lib/XS.php';
//error_reporting(E_ALL ^ E_NOTICE);

class Search
{
    private $index;
    private $search;
    private $project;

    function __construct($project)
    {
        //载入引导文件
        include('sdk/php/lib/XS.php');
        //初始化
        $xs = new \XS($project);
        $this->project = $project;
        $this->index = $xs->index;
        $this->search = $xs->search;
        $this->search->setCharset('UTF-8');
    }

    public function query($keyword, $page = 1, $limit = 10, $subject = null)
    {
        $response = array();
        # 设置搜索语句
        $this->search->setQuery($keyword);
        # 增加附加条件：提升标题中包含 'xunsearch' 的记录的权重
        //$this->search->addWeight('subject', 'xunsearch');
        # 设置返回结果最多条数限制，并设置起始节点
        if (!is_numeric($page) || $page < 1) $page = 1;
        if (!is_numeric($limit)) $limit = 10;
        $start = ($page - 1) * $limit;
        $this->search->setLimit($limit, $start);
        # 执行搜索，将搜索结果文档保存在data对象中
        $response['data'] = $this->search->search($keyword);
        # 获取搜索结果的匹配总数估算值
        $response['count'] = $this->search->count();
        return $response;
    }
}